import 'package:flutter/material.dart';
import 'package:flutter_simple_treeview/flutter_simple_treeview.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/evaluationSkillType.dart';
import 'package:ichinesereader/models/evaluation/proficiencySkillsResult.dart';
import 'package:ichinesereader/pages/common/circularImage.dart';
import 'package:ichinesereader/widgets/grids/evaluationProficiencySkillProgressDataGrid.dart';
import 'package:syncfusion_flutter_gauges/gauges.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../../themes/appTheme.dart';

class EvaluationProficiencySkillsTreeview extends StatefulWidget {
  EvaluationProficiencySkillsTreeview({Key? key}) : super(key: key);

  @override
  EvaluationProficiencySkillsTreeviewState createState() =>
      EvaluationProficiencySkillsTreeviewState();
}

class EvaluationProficiencySkillsTreeviewState
    extends State<EvaluationProficiencySkillsTreeview> {
  final EvaluationController _evaluationController = Get.find();
  final box = Hive.box('appconfig');
  late List<ProficiencySkillsDataTree> _evaluationSkillsDataTree;
  final TreeController _treeController = TreeController(allNodesExpanded: true);
  String _skillType = Constants.evaluationSkillTypes[0].skill.toString();
  String _classId = '';
  bool isTeacher = false;

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    if (isTeacher) {
      _classId = box.get(CacheManagerKey['currentclass'].toString());
    } else {
      _classId = '';
    }

    Future.delayed(Duration(milliseconds: 200), () {
      _evaluationController.fetchEvaluationProficiencySkillsData(
          _classId, _evaluationController.currentLevel.value.toString(), '');
    });

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void setSkillType(String type) {
    setState(() {
      _skillType = type;
    });
  }

  List<TreeNode> generateTree(ProficiencySkillsDataTree root) {
    var nodes = <TreeNode>[];
    nodes.add(toTreeNodes(root));
    return nodes;
  }

  TreeNode toTreeNodes(ProficiencySkillsDataTree node) {
    var result = new TreeNode();
    if (node.skills != null) {
      result = TreeNode(
          key: ValueKey(node.id),
          content: rectangleWidget(node),
          children: node.skills!.map((element) {
            return toTreeNodes(element);
          }).toList());
    }
    return result;
  }

  Widget buildTree(String type) {
    try {
      ProficiencySkillsDataTree rootTree = this
          ._evaluationSkillsDataTree
          .where((tree) => tree.name == type)
          .first;
      return TreeView(
        nodes: generateTree(rootTree),
        treeController: _treeController,
      );
    } on FormatException catch (e) {
      return Text(e.message);
    }
  }

  buildFloatingActionButtons() {
    List<EvaluationSkillType> skillTypes = Constants.evaluationSkillTypes
        .where((element) => element.skill != 'AI Speaking')
        .toList();

    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: skillTypes
          .map((state) => Padding(
                padding: const EdgeInsets.symmetric(vertical: 3.0),
                child: SizedBox(
                  width: 45.0,
                  height: 45.0,
                  child: FloatingActionButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(3.0),),),
                    // heroTag: state.skill.toString(),
                    // tooltip: state.skill!.tr,
                    onPressed: () {
                      setSkillType(state.skill.toString());
                    },
                    elevation: 5,
                    splashColor: Colors.grey,
                    backgroundColor: Colors.white,
                    child:
                    // Icon(
                    //   Icons.record_voice_over,
                    //   color: Get.isDarkMode
                    //       ? Colors.black
                    //       : AppTheme.colors.pinkBtn,
                    //   size: 30.0,
                    // ),
                    Image.asset(
                      state.image.toString(),
                      width: 50,
                      height: 50,
                    ),
                  ),
                ),
              ))
          .toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    box.put('SkillType', 'Proficient');
    Log.debug(
        'Build evaluation proficiency skills treeview teacher/student graph');
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: buildFloatingActionButtons(),
      floatingActionButtonLocation: FloatingActionButtonLocation.miniEndDocked,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              ///////树状图的背景//////
              child: Container(
                width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(3.0),
              color: Get.isDarkMode
                  ? AppTheme.colors.darkTheme2
                  : Colors.white.withOpacity(0.3),
            ),
            padding: EdgeInsets.only(
              top: 30.0,
            ),
            child: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: _evaluationController.obx(
                  (data) {
                    _evaluationSkillsDataTree =
                        _evaluationController.evaluationSkillsDataTree;
                    if (_evaluationSkillsDataTree.isNotEmpty) {
                      return buildTree(_skillType);
                    } else {
                      return Text('');
                    }
                  },
                  onEmpty: Center(child: Text('Data not available ...'.tr)),
                  onLoading: Container(),
                ),
              ),
            ),
          ))
        ],
      ),
    );
  }

  Widget rectangleWidget(dynamic node) {
    ProficiencySkillsDataTree tree = node as ProficiencySkillsDataTree;
    double _percentage = tree.progress != 0 && tree.total != 0
        ? (tree.progress! / tree.total!) * 100
        : 0;

    String image =
        'https://resources.ichinesereader.com/media/evaluation/bubble_blue_${tree.progress}.gif';
    return InkWell(
      onTap: () {
        Log.debug(tree.id);
        if (isTeacher) {
          // Get.to(() => EvaluationProficiencySkillProgressTreeMap(
          //       level: _currentLevel.toString(),
          //       skillId: tree.id.toString(),
          //       skillTitle: tree.name.toString(),
          //     ));
          Get.to(() => EvaluationProficiencySkillProgressDataGrid(
                level: _evaluationController.currentLevel.value.toString(),
                skillId: tree.id.toString(),
                skillTitle: tree.name.toString(),
              ));
        }
      },
      ////////单个技能选项方块////////
      child: Container(
          margin: EdgeInsets.all(6.0),
          padding: EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: Get.isDarkMode
                ? Colors.black.withOpacity(0.6)
                : Colors.white.withOpacity(0.6),
            borderRadius: BorderRadius.circular(12.0),
            boxShadow: [
              BoxShadow(
                blurRadius: 9.0,
                spreadRadius: 1.0,
                color: Get.isDarkMode
                    ? Colors.transparent
                    : Get.theme.primaryColor.withOpacity(0.3),
                offset: Offset(12.0, 12.0),
              ),
            ],
          ),
          child: Row(
            children: [
              Container(
                width: 60,
                height: 60,
                child: SfRadialGauge(
                  axes: [
                    RadialAxis(
                        minimum: 0,
                        maximum: 100,
                        startAngle: 0,
                        endAngle: 360,
                        interval: 1,
                        showTicks: false,
                        showLabels: false,
                        axisLineStyle: AxisLineStyle(thickness: 6),
                        pointers: <GaugePointer>[
                          RangePointer(
                              value: _percentage,
                              width: 6,
                              color: Colors.tealAccent[200],
                              cornerStyle: CornerStyle.bothCurve)
                        ],
                        showFirstLabel: false,
                        annotations: <GaugeAnnotation>[
                          GaugeAnnotation(
                              widget: NonCacheCircularImage(image, 60),
                              angle: 90,
                              positionFactor: 0)
                        ])
                  ],
                ),
              ),
              SizedBox(
                width: 6.0,
              ),
              Text(tree.name.toString(),
                  style: TextStyle(
                    color: Get.isDarkMode
                        ? Get.theme.primaryColorDark
                        : Colors.black,
                  )),
            ],
          )),
    );
  }
}
